<?php

class FormElement_AjaxCheckboxes extends AbstractAssociationElement
{

  public function beforeAction()
  {
    $request = s::request();

    if ($request->post('formAction') == 'toggle' && $request->post('name') == $this->getName()) {
      $at = $this->getAssocTable();
      $apk = $this->getAssocPrimaryKey();
      $afk = $this->getAssocForeignKey();

      $apid = $request->post($apk);
      $afid = $request->post($afk);

      $data = array($afk => $afid, $apk => $apid);

      $checked = $request->post('checked');

      if ($checked) {
        $rs = DB::getInstance()->insert($at, $data)->execute($data);
      }
      else {
        $rs = DB::getInstance()->delete($at, "$afk = :$afk AND $apk = :$apk")->execute($data);
      }
    }
  }

  public function render($row, $action)
  {
    switch ($action) {
      case Form::ACTION_VIEW :

        $options = $this->getOptions();
        $values = $this->getValues($row);

        $options = array_intersect_key($options, array_flip($values));

        $html = new HTMLElement('p');
        $html->append("<label>{$this->getTitle()}:</label> ");

        $output = $html->append(implode(', ', $options));

        break;

      default :
        $this->beforeRender($row, $action);

        $options = $this->getOptions();

        $this->set('route', sy_fix_extension(s::request()->route(), 'json'));
        $this->set('value', $this->getValue($row));
        $this->set('values', $this->getValues($row));
        $this->set('options', $options);
        $this->set('key', $this->assocForeignKey);
        $this->set('rowClass', $this->getRowClass($row));
        $this->set('class', $this->getClass($row, $action));
        $this->set('action', $action);
        $this->set('name', $this->name);
        $this->set('title', $this->title);
        $this->set('typeClass', $this->getTypeClass());
        $this->set('instanceClass', $this->getInstanceClass());
        $this->set('enabled', $this->enabled);

        $output = $this->getView();

        $output = $this->afterRender($output, $row, $action);
    }

    return $output;
  }

}

?>